<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Repository\LinmaoRepository;
use App\Http\Repository\OmsRepository;
use Illuminate\Console\Command;

class pullProcessingLM extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:pullProcessingLM {--processing_code=} {--modifiedBegin=} {--modifiedEnd=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步数加成品加工单--领猫';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $processingCode = $this->option('processing_code') ?: "";
        $modifiedBegin = $this->option('modifiedBegin') ?: date('Y-m-d H:i:s', strtotime("- 1 hour"));
        $modifiedEnd = $this->option('modifiedEnd') ?: date('Y-m-d H:i:s');
        $res = (new LinmaoRepository())->getbills(['page' => 1, 'size' => 100, 'codes' => $processingCode, 'modifiedBegin' => $modifiedBegin, 'modifiedEnd' => $modifiedEnd]);
        if(!isset($res['data']['datas'])){
            echo "请求接口异常: ".json_encode($res, JSON_UNESCAPED_UNICODE)."\n";
            die;
        }
        //七月夕拉取采购单 1、满足可下拉的采购单号  2、2025-04-10下的采购单
        $validCodes = ["PO20250403015","PO20250403016","PO20250403017","PO20250318004","PO20250324002", "PO20250325005","PO20250328001","PO20250328002",
            "PO20250317003","PO20250318003","PO20250321011","PO20250321013","PO20250322003","PO20250324009","PO20250324010", "PO20250324011","MO20250328002",
            "PO20250403018","PO20250403019","PO20250403005","PO20250403006","PO20250403007","PO20250409001","PO20250409002", "PO20250320003","PO20250318008",
            "PO20250318009","PO20250311010","PO20250321004","PO20250311011","PO20250311007", "PO20250321001","PO20250321002", "PO20250321003","PO20250321006",
            "PO20250321007","PO20250321008","PO20250321009","PO20250324005","PO20250324006", "PO20250324007","PO20250324008","PO20250327001","PO20250403008",
            "PO20250403013","PO20250403014","PO20250403009","PO20250403010","PO20250325001", "PO20250403011","PO20250403012","PO20250325002","PO20250327002",
            "PO20250403020", "PO20250407001","MO20250311001","PO20250403002", "MO20250321003","MO20250321004","MO20250324001","MO20250324002","MO20250324007",
            "MO20250325002","MO20250328001", "MO20250331001","MO20250403003","MO20250403005","MO20250403006","MO20250314008","MO20250314009","MO20250324003",
            "MO20250314002", "MO20250314003","MO20250314004","MO20250403008","MO20250325006","MO20250325003","MO20250403004","MO20250403001",
            "MO20250403007"];
        foreach ($res['data']['datas'] as $item){
            if(!in_array($item['code'], $validCodes) && date('Y-m-d H:i:s', strtotime($item['createTime'])) < "2025-04-10 00:00:00"){
                echo $item['code']." {$item['createTime']}, 该加工单不在拉取规则内\n";
                continue;
            }
            $createTime = date('Y-m-d H:i:s');
            foreach ($item['subs'] as $skuObj){
                $exist = (new SsyProcessingListTable())->where('type_no', $item['pdtCodes'])->where('processing_code', $item['code'])->where('sku_code', $skuObj['skuCode'])->first();
                echo "正在执行：{$item['code']} {$item['pdtCodes']} {$skuObj['skuCode']} ";
                $isOms = !empty($item['apiCode']) && str_starts_with($item['apiCode'], "PO") ? 1 : 0;
                $jyPurchaseNumber = null;
                if($isOms){
                    //获取采购通知单号
                    $pnoRes = OmsRepository::searchPno($item['code']);
                    if($pnoRes['order'][0]['purchaseNoticeOrderCode'] ?? ""){
                        $jyPurchaseNumber = $pnoRes['order'][0]['purchaseNoticeOrderCode'];
                    }
                }
                if(empty($exist)){
                    $data = [
                        "processing_code"     => trim($item['code']),//成品加工单编码
                        "factory_contract_no" => trim($item['contractCode'] ?? ""),//工厂合同号
                        "factory_name"        => trim($item['supplierName']),//供应商
                        "supplier_id"         => trim($item['supplierCode']),//供应商id
                        "contract_date"       => trim($item['ovDate']),//合同交期
                        "merchandiser"        => trim($item['followMan']),//跟单人
                        "order_processor"     => trim($item['followMan']),//理单员
                        "countnum"            => trim($item['totalQty']),//总件数
                        "num"                 => trim($skuObj['qty']),//总件数
                        "bunum"               => trim($skuObj['qty'])+(trim($skuObj['qty'])*0.05),//加工单数加溢出数
                        "countprice"          => trim($item['totalAmt']),//总价
                        "advance_charge"      => trim($item['paidAmount']),//预付款
                        //"embroidery_price"    => trim($item['f8_price']),//绣花厂单价
                        "production_date"     => trim($skuObj['deliverDate']),//生产回复交期
                        //"verify_price_number" =>trim($item['verify_price_number']),//大货核价编码
                        "type_no"             => trim($item['pdtCodes']),//款号
                        "type_name"           => trim($skuObj['pdtName']),//款名
                        "color_code"          => trim($skuObj['colorCode']),//颜色编码
                        "size_code"           => trim($skuObj['sizeCode']),//尺码编码
                        "unit_price"          => trim($skuObj['taxPrice']),//单价
                        "add_date"            => date('Y-m-d', strtotime($item['orderDate'])),//客人下单时间
                        "sku_code"            => $skuObj['skuCode'],//sku
                        "source_type"         => 2,//加工单接口获取
                        "s_status"            => $item['statuz'] == 0 ? 0 : 1, //审核状态 0 未审核 1 已审核
                        "f_status"            => $item['statuz'] == 9 ? 2 : ($item['statuz'] == 7 ? 1: 0), //2异常禁用 1完结 0进行中
                        "export_order_number" => trim($item['rocode']), //运营订单编号
                        "createtime"          => $item['createTime'],
                        "updatetime"          => $item['modifyTime'],
                        "tb_time"             => $createTime,
                        "adduser"             => $item['createUser'],
                        "status"              => $item['statuz'] == 9 ? 0 : 1,//0禁用 1启用
                        "is_oms"              => $isOms,
                        "jy_number"           => $isOms ? $item['apiCode'] : "",
                        "jy_purchase_number"  => $jyPurchaseNumber,
                        "brand_name"          => "七月夕",
                        "brand_code"          => "Q",
                    ];
                    echo "创建成功\n";
                    (new SsyProcessingListTable())->createData($data);
                }else{
                    if($exist->updatetime == $item['modifyTime']){
                        echo "数据暂未更新, 无需同步\n";
                        continue;
                    }
                    if($exist->f_status == 1){
                        echo "数据已完结, 无需同步\n";
                        continue;
                    }
                    $data = [
                        "factory_contract_no" => trim($item['contractCode'] ?? ""),//工厂合同号
                        "factory_name"        => trim($item['supplierName']),//供应商
                        "supplier_id"         => trim($item['supplierCode']),//供应商id
                        "contract_date"       => trim($item['ovDate']),//合同交期
                        "merchandiser"        => trim($item['followMan']),//跟单人
                        "order_processor"     => trim($item['followMan']),//理单员
                        //"countnum"            => trim($item['totalQty']),//总件数
                        //"num"                 => trim($skuObj['qty']),//总件数
                        //"bunum"               => trim($skuObj['qty'])+(trim($skuObj['qty'])*0.05),//加工单数加溢出数
                        "countprice"          => trim($item['totalAmt']),//总价
                        "advance_charge"      => trim($item['paidAmount']),//预付款
                        "production_date"     => trim($skuObj['deliverDate']),//生产回复交期
                        "type_name"           => trim($skuObj['pdtName']),//款名
                        "unit_price"          => trim($skuObj['taxPrice']),//单价
                        "add_date"            => date('Y-m-d', strtotime($item['orderDate'])),//客人下单时间
                        "s_status"            => $item['statuz'] == 0 ? 0 : 1, //审核状态 0 未审核 1 已审核
                        "f_status"            => $item['statuz'] == 9 ? 2 : ($item['statuz'] == 7 ? 1: 0), //2异常禁用 1完结 0进行中
                        "export_order_number" => trim($item['rocode']), //运营订单编号
                        "updatetime"          => $item['modifyTime'],
                        "status"              => $item['statuz'] == 9 ? 0 : 1,//0禁用 1启用
                        "is_oms"              => $isOms,
                        "jy_number"           => $isOms ? $item['apiCode'] : "",
                        "jy_purchase_number"  => $jyPurchaseNumber,
                    ];
                    echo "更新成功\n";
                    (new SsyProcessingListTable())->updateData($exist->id, $data);
                }
            }
        }
    }
}
